import axios from 'axios'
import { size } from 'lodash'
import React, { Component } from 'react'
import MyScroll from '../../components/better-scroll/MyScroll'

export default class Demo extends Component {
  state = {
    list: [],
    page: 1,
    size: 5,
  }

  // 请求数据函数
  fetchList = async () => {
    const res = await axios.get('/api/list')
    return res.data.data.list
  }

  // 第一次请求前5条数据
  async componentDidMount() {
    const list = await this.fetchList()
    this.setState({
      list: list.slice(0, 5),
    })
  }

  render() {
    return (
      <MyScroll
        // 下拉
        pullDown={(func) => {
          func()
        }}
        // 上拉
        pullUp={async (func) => {
          this.setState({
            page: this.state.page + 1,
          })
          const { page, size } = this.state
          // 请求数据。拼接数据
          this.fetchList().then((res) => {
            this.setState({
              list: [...this.state.list, ...res.slice((page - 1) * size, page * size)],
            })
            func()
          })
        }}
      >
        {this.state.list.map((item, index) => {
          return (
            <div key={item.id} style={{ width: 200, height: 300, margin: 10, background: 'lightblue' }}>
              {index}
            </div>
          )
        })}
      </MyScroll>
    )
  }
}
